package com.gticket.orderservice.handler;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.gticket.orderservice.pojo.*;
import com.gticket.orderservice.service.ActualSeatService;
import com.gticket.orderservice.service.AlipayService;
import com.gticket.orderservice.service.OrderItemService;
import com.gticket.orderservice.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: 伴你时光尽头
 * @Date: 2019/11/18 16:12
 */
@RestController
@Slf4j
public class PayHandler {
    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private ActualSeatService actualSeatService;
    @Autowired
    private RabbitTemplate template;

    //传入databasename  订单总价  订单num 封装为Orders对象
    @CrossOrigin(origins = "*")
    @GetMapping("/pay")
    public void pay(Orders orders, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //将订单号和数据库名存入session
//        request.getSession().setAttribute("order_num",orders.getOrder_num());
//        request.getSession().setAttribute("databasename",orders.getDatabasename());
        System.out.println("执行支付");
        //订单总价
//        System.out.println(orders.getTotalprice());
//        //订单号
//        System.out.println(orders.getOrder_num());
        //通过订单pojo对象中封装的databasename查询当前影院的商家支付信息封装为Alipay对象
        orders = orderService.getOrdersByOrder_num(orders);
        log.error("为订单号为：" + orders.getOrder_num() + "  的订单执行支付");
        Alipay alipay = alipayService.getAlipay(orders);
        System.out.println(alipay.toString());
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipay.getGatewayUrl(), alipay.getApp_id(), alipay.getMerchant_private_key(), "json", alipay.getCharset(), alipay.getAlipay_public_key(), alipay.getSign_type());
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipay.getReturn_url());//同步
        alipayRequest.setNotifyUrl(alipay.getNotify_url());//异步
        //商户订单号，商户网站订单系统中唯一订单号，必填
		/*String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
		//付款金额，必填
		String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
		//订单名称，必填
		String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
		//商品描述，可空
		String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");*/
        //从session中取出订单号
        //订单号
        //cutDownOrder(out_trade_no);
        //付款金额
        //订单名称
        String subject = alipay.getCinema_name();
//        if(check!=null){
//            check_cart = check;
//            for(String c:check_cart){
//                System.out.println(c);
//            }
//        }
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + new String(orders.getOrder_num().getBytes("ISO-8859-1"), "UTF-8") + "\","
                + "\"total_amount\":\"" + orders.getTotalprice() + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        response.setContentType("text/html;charset=utf-8");
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        template.convertAndSend(ExchangeName.IMMEDIATE, "order", new String(orders.getDatabasename()+"."+"收到一条新订单，订单编号为："+orders.getOrder_num()));
        //输出
        log.error("跳转支付页面");
        response.getWriter().println(result);
    }

    @CrossOrigin(origins = "*")
    @PostMapping("/return_notify")
    public void return_notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        //通过request获取请求url截取域名
//        StringBuffer url = request.getRequestURL();
//        String[] tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString().substring(7).split("\\.");
        //异步通知
        System.out.println("执行异步通知");
        log.error(request.getParameter("out_trade_no") + "订单异步通知到位，准备执行异步通知");
        //通过订单pojo对象中封装的databasename查询当前影院的商家支付信息封装为Alipay对象
        Alipay alipay = alipayService.getAlipay(orderService.getOrdersByOrder_num(new Orders((String) request.getSession().getAttribute("databasename"), (String) request.getSession().getAttribute("order_num"))));
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay.getAlipay_public_key(), alipay.getCharset(), alipay.getSign_type()); //调用SDK验证签名
        //——请在这里编写您的程序（以下代码仅作参考）——
			/* 实际验证过程建议商户务必添加以下校验：
			1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
			2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
			3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
			4、验证app_id是否为该商户本身。
			*/
        signVerified = true;
        System.out.println(signVerified);
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            if (trade_status.equals("TRADE_FINISHED")) {
                System.out.println("执行finished代码");
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                System.out.println("执行success中代码");
                //支付成功，通过订单号码将对应的订单找到，传入支付号码和修改订单状态----1
                //然后根据订单号码 去订单项将对应所有的项目的状态改为未使用----1
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
                //如果成功，将支付宝交易号和交易状态通过订单号码存在数据库表中去
                //将支付宝交易号存入到对应的订单中
                orderService.setPay_num(new Orders((String) request.getSession().getAttribute("databasename"), out_trade_no, trade_no));
                log.error(out_trade_no + "订单  获得支付号并将支付号插入到对应的订单中 支付号为：" + trade_no);
                //更爱订单状态为已支付1
                orderService.updateStateToAlreadyPay(new Orders((String) request.getSession().getAttribute("databasename"), out_trade_no));
                log.error("订单支付成功，修改订单状态为已支付");
                //创建订单取票码
                String ticketnum = UUID.randomUUID().toString().replaceAll("-", "");
                log.error("为订单" + out_trade_no + "生成取票码" + ticketnum + "并插入");
                orderService.setTicketnum(new Orders((String) request.getSession().getAttribute("databasename"), out_trade_no, ticketnum));
                //template.convertAndSend(ExchangeName.IMMEDIATE, "order", new String((String) request.getSession().getAttribute("databasename")+".收到新订单，订单号为："+out_trade_no);
            }
            response.getWriter().print("success");
        } else {//验证失败
            response.getWriter().print("fail");

        }
    }
    @CrossOrigin(origins = "*")
    @GetMapping("/return_url")
    public void return_url(HttpServletResponse response, HttpServletRequest request) {
        System.out.println("执行同步通知");
        try {
            log.error("支付成功 同步通知到达");
            response.sendRedirect("/index.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //orders封装databasename和order_num
    @CrossOrigin(origins = "*")
    @GetMapping("/tuikuan")
    //退款接口
    public String tuikuan(Orders orders) throws Exception {
        //获取完整订单信息
        orders = orderService.getOrdersByOrder_num(orders);
        log.error("准备为订单" + orders.getOrder_num() + "进行退款操作");
        // 比较 年 月 日
        //创建日期转换对象：年月日 时分
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        boolean flag = false;
        //用于判断时间是否符合要求   开演30分钟后无法退票
        String date = orderService.getMovieStartTime(orders);
        //假设 设定日期是 2018-11-11 11:11
        Date now = new Date();
        //今天 实际日期是  Debug：Wed Nov 12 12:00:18 CST 2018
        try {
            Date dateD = sdf.parse(date);
            //转换为 date 类型 Debug：Sun Nov 11 11:11:11 CST 2018
            flag = (dateD.getTime() + 30 * 60 * 1000) >= now.getTime();
            System.err.println("flag = " + flag);
            // flag = false
            log.error("判断退票时间是否超过时效");
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if (flag&&1==orders.getOrder_state()) {
            log.error("执行退款");
            //获取当前支付配置
            Alipay alipay = alipayService.getAlipay(orders);
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                    alipay.getApp_id(),
                    alipay.getMerchant_private_key(),
                    "json",
                    "utf-8",
                    alipay.getAlipay_public_key(),
                    "RSA2");
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":" + orders.getOrder_num() + "," +
                    "\"trade_no\":" + orders.getPay_num() + "," +
                    "\"refund_amount\":" + orders.getTotalprice() + "}");
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                System.out.println("调用成功");
                //修改订单状态为已取消
                orderService.updateStateToAlreadyCancel(orders);
                Integer as_id = null;
                List<OrderItems> items = orderItemService.getItemsByOrder_num(orders);
                for (OrderItems item : items) {
                    item.setDatabasename(orders.getDatabasename());
                    log.error("座位释放row：" + item.getRow() + "col:" + item.getCol());
                    //根据订单项  将座位表修改
                    ActualSeat actualSeat = actualSeatService.selectActualSeatByAs_id(item);
                    as_id = actualSeat.getAs_id();
                    //通过反射获取当前订单中座位的行
                    Class<?> ActualSeat = Class.forName("com.gticket.orderservice.pojo.ActualSeat");
                    Object obj = ActualSeat.newInstance();
                    Method method = ActualSeat.getDeclaredMethod("getRow_" + item.getRow(), null);
                    String temp = (String) method.invoke(actualSeat);//指定行
                    StringBuffer stemp = new StringBuffer(temp);
                    stemp.replace(item.getCol() - 1, item.getCol(), "1");
                    //反射设置对应行
                    actualSeat = new ActualSeat();
                    actualSeat.setDatabasename(item.getDatabasename());
                    Method method1 = ActualSeat.getDeclaredMethod("setRow_" + item.getRow(), String.class);
                    method1.invoke(stemp.toString());
                    actualSeat.setAs_id(as_id);
                    actualSeatService.changeRow(actualSeat);
                    actualSeat = null;
                }
                return "退款成功";
            } else {
                System.out.println("调用失败");
                return "退款失败";
            }
        } else {
            log.error("开场30分钟或者已取票后，退票退款失败");
            return "开场30分钟后或者已取票后，不能退票";
        }
    }
}
